package filejoiner.io;

import java.io.*;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author Luis
 */
public class Serializer {

    private ObjectOutputStream objectOutputStream;
    private ObjectInputStream objectInputStream;
    private FileOutputStream fileOutputStream;
    private FileInputStream fileInputStream;
    private File file;

    public Serializer(String path, String name) {
        file = new File(path + name);
    }

    public void serialize(Object object) {
        try {
            fileOutputStream = new FileOutputStream(file);
            objectOutputStream = new ObjectOutputStream(fileOutputStream);
            objectOutputStream.writeObject(object);
        } catch (IOException ex) {
            Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                objectOutputStream.flush();
                objectOutputStream.close();
                fileOutputStream.flush();
                fileOutputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public Object read() {
        Object object = null;
        try {
            fileInputStream = new FileInputStream(file);
            objectInputStream = new ObjectInputStream(fileInputStream);
            object = objectInputStream.readObject();
        } catch (ClassNotFoundException ex) {
            Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
        } finally {
            try {
                objectInputStream.close();
                fileInputStream.close();
            } catch (IOException ex) {
                Logger.getLogger(Serializer.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return object;
    }
}
